package com.rbac.web.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rbac.web.db.PermissionDAO;
import com.rbac.web.db.PermissionDO;
import com.rbac.web.exception.InfrastructureException;
import com.rbac.web.model.PageResult;
import com.rbac.web.model.PageV0;
import com.rbac.web.model.Permission;
import com.rbac.web.model.PermissionType;
import com.rbac.web.service.IPermissionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author gengaoliu
 */
@Service
@RequiredArgsConstructor
public class PermissionServiceImpl implements IPermissionService {

  final PermissionDAO dao;

  @Override
  public void insert(Permission permission) {
    Optional.of(
            dao.selectOne(
                Wrappers.<PermissionDO>lambdaQuery()
                    .eq(PermissionDO::getName, permission.getName())))
        .ifPresent(
            x -> {
              if (PermissionType.MENU.getValue().equals(x.getType())) {
                throw InfrastructureException.createException("The menu name cannot be repeated");
              }
            });
    dao.insert(PermissionDO.from(permission));
  }

  @Override
  public void updateByEntity(Permission permission) {
    dao.updateById(PermissionDO.from(permission));
  }

  @Override
  public void deleteById(Integer id) {
    dao.deleteById(id);
  }

  @Override
  public List<Permission> findAll() {
    return dao.selectList(null).stream().map(PermissionDO::toPermission).toList();
  }

  @Override
  public PageResult<Permission> selectPage(PageV0 pageV0) {
    IPage<PermissionDO> all = dao.selectPage(Page.of(pageV0.getPage(), pageV0.getSize()), null);
    List<Permission> list = all.getRecords().stream().map(PermissionDO::toPermission).toList();
    return PageResult.of(all.getCurrent(), all.getSize(), all.getTotal(), list);
  }

  @Override
  public List<Permission> findAllByIds(List<Integer> permissionIds) {
    return dao.selectBatchIds(permissionIds).stream().map(PermissionDO::toPermission).toList();
  }
}
